package com.antd.modules.security.service;

import com.antd.common.utils.PageUtils;
import com.antd.common.utils.Query;
import com.antd.common.utils.R;
import com.antd.modules.security.dao.SecConnectModularDao;
import com.antd.modules.security.dao.SecDataDao;
import com.antd.modules.security.dao.SecEquipmentDao;
import com.antd.modules.security.entity.SecConnectModular;
import com.antd.modules.security.entity.SecData;
import com.antd.modules.security.entity.SecEquipment;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class SecRealTimeDataService {
    @Resource
    private SecDataDao secDataDao;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private SecConnectModularDao secConnectModularDao;
    @Resource
    private SecEquipmentDao secEquipmentDao;
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SecData> page = secDataDao.queryPageWithMoreInfo(new Query<SecData>().getPage(params), params);
        List<SecData> records = page.getRecords();
        Set<String> keys = redisTemplate.keys("instructData*");
        List<Object> objects = redisTemplate.opsForValue().multiGet(keys);
        for(SecData temp : records){
            SecData realTimeData = getRealTimeData(objects, temp.getId());
            if(realTimeData != null){
                temp.setCurData(realTimeData.getCurData());
                temp.setFetchTime(realTimeData.getFetchTime());
            }
        }
        return new PageUtils(page);
    }
    private SecData getRealTimeData(List<Object> cacheDatas,Integer id){
        for(Object item : cacheDatas){
            SecData temp = (SecData) item;
            if(temp.getId().equals(id)){
                return temp;
            }
        }
        return null;
    }
    public R modularsAndEquipments(){
        List<SecConnectModular> modularList = secConnectModularDao.selectList(new QueryWrapper<>());
        List<SecEquipment> equipments = secEquipmentDao.selectList(new QueryWrapper<>());
        return R.ok().put("modulars",modularList).put("equipments",equipments);
    }
}
